﻿namespace com.crownpack.Extensions.TimeSpanExtensions
{
    using System;
    using System.Text;

    public static class TimeSpanExtensions
    {
        #region Methods

        /// <summary>
        /// Returns the timespan value as total hours minutes seconds where the total hours are greater 0, otherwise returns the value as minutes seconds.
        /// For example: 
        /// TimeSpan ts = TimeSpan( 0, 0, 0, 3, 550 );
        /// Console.WriteLine( ts.FormatAsTotalHoursMinutesSeconds( ) ); 
        /// returns: 3.55 seconds
        /// 
        /// TimeSpan ts = new TimeSpan( 0, 3, 0, 3, 550 );
        /// Console.WriteLine( ts.FormatAsTotalHoursMinutesSeconds( ) ); 
        /// returns: 3 hours 0 minutes and 3.55 seconds
        /// 
        /// TimeSpan ts = new TimeSpan( 1, 3, 0, 3, 550 );
        /// Console.WriteLine( ts.FormatAsTotalHoursMinutesSeconds( ) ); 
        /// returns: 27 hours 0 minutes and 3.55 seconds
        /// </summary>
        /// <param name="ts"></param>
        /// <returns></returns>
        public static string FormatAsTotalHoursMinutesSeconds( this TimeSpan ts )
        {
            StringBuilder sb = new StringBuilder( );
            int t = ts.Hours + ( ts.Days * 24 );
            if ( t > 0 )
                sb.AppendFormat( "{0} hour{1} ", t, t <= 0 || t > 1 ? "s" : string.Empty );
            if ( t > 0 || ts.Minutes > 0 )
                sb.AppendFormat( "{0} minute{1} and ", ts.Minutes, ts.Minutes <= 0 || ts.Minutes > 1 ? "s" : string.Empty );
            sb.AppendFormat( "{0}{2} second{1}", ts.Seconds, ts.Seconds <= 0 || ts.Seconds > 1 || ts.Milliseconds > 0 ? "s" : string.Empty, ts.Milliseconds > 0 ? string.Format( ".{0}", ts.Milliseconds.ToString( ).TrimEnd( '0' ) ) : string.Empty );

            string s = sb.ToString( );
            sb = null;
            return s;
        }

        public static int GetTotalHoursUnrounded( this TimeSpan ts )
        {
            return ts.Hours + ( ts.Days * 24 );
        }

        #endregion Methods
    }
}